package com.sc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 自定义RedisTemplate配置
 */

@Configuration
public class RedisConfig {
    /**
     * 向容器中注入RedisTemplate，并将key的序列化器改为String序列化器(jdk可以转换所有类型，String只能转换)
     * @param redisConnectionFactory  redis连接工厂
     * @return  redisTemplate对象
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        //redisTemplate的字符串和hash类型数据的序列化器都是jdk序列化器（将key改为String序列化器）
        //字符串类型工厂配置
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        //hash类型工厂配置
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new JdkSerializationRedisSerializer());

        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}
